# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

_realname=oneTBB
pkgbase=mingw-w64-tbb
pkgname=("${MINGW_PACKAGE_PREFIX}-tbb")
pkgver=2022.1.0
pkgrel=2
pkgdesc='oneAPI Threading Building Blocks (mingw-w64)'
arch=(any)
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://software.intel.com/en-us/oneapi/onetbb'
msys2_repository_url="https://github.com/uxlfoundation/oneTBB"
msys2_references=(
  "cpe: cpe:2.3:a:intel:threading_building_blocks"
)
license=('spdx:Apache-2.0')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-hwloc")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("https://github.com/uxlfoundation/oneTBB/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        001-fix-using-TBB-with-Debug-build-type.patch
        002-fix-link-flags-on-mingw.patch
        003-fix-getting-assembler-version-on-mingw.patch)
sha256sums=('ed067603ece0dc832d2881ba5c516625ac2522c665d95f767ef6304e34f961b5'
            '094c556a1087563a3a5810db0fa81aed6432b3a8e91aab9a747e9a55ea262f2a'
            '7105abda9ae82825bb7df12ed5bfba698b896945fca0023dcd040e51b3b7f1cf'
            'cdac0450805f106220ac087b867b10af5066dc01a4272c037b0de2b7f53d0fe1')

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd ${_realname}-${pkgver}
  apply_patch_with_msg \
    001-fix-using-TBB-with-Debug-build-type.patch \
    002-fix-link-flags-on-mingw.patch \
    003-fix-getting-assembler-version-on-mingw.patch

  find . -name "*.orig" -exec rm -f {} \;
}

build() {
  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ ${CC} == gcc ]]; then
    _extra_config+=("-DTBB_ENABLE_IPO=OFF")
  else
    _extra_config+=("-DTBB_ENABLE_IPO=ON")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -GNinja \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DTBB_TEST=OFF \
    -DTBB_STRICT=OFF \
    -DBUILD_SHARED_LIBS=ON \
    -S ${_realname}-${pkgver} \
    -B build-${MSYSTEM}

  ${MINGW_PREFIX}/bin/cmake --build build-${MSYSTEM}
}

package() {
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install build-${MSYSTEM}
  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/LICENSE.txt \
    "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
